package com.example.element.module.jetpack.livedata

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActJetpackLivedataBinding
import com.example.element.module.jetpack.lifecycles.MyObserver

class LiveDataActivity : AbsActivity<ActJetpackLivedataBinding>() {

    companion object {
        @JvmStatic
        fun open(context: Context) {
            context.startActivity(Intent(context, LiveDataActivity::class.java))
        }
    }

    private lateinit var sp: SharedPreferences
    private lateinit var viewModel: LiveDataViewModel

    override fun getLayoutId() = R.layout.act_jetpack_livedata

    override fun main() {
        sp = getPreferences(Context.MODE_PRIVATE)
        viewModel = ViewModelProvider(this, LiveDataViewModelFactory(sp.getInt("", 0))).get(LiveDataViewModel::class.java)
        refreshCounter()
//        lifecycle.addObserver(MyObserver())
        viewModel.counter.observe(this, Observer { count ->
            mBinding.infoText.text = count.toString()
        })
    }

    override fun initListener() {
        mBinding.clearCount.setOnClickListener {
            viewModel.clear()
        }

        mBinding.plusOneBtn.setOnClickListener {
            viewModel.plusOne()
        }
    }

    private fun refreshCounter() {
        mBinding.infoText.text = viewModel.counter.toString()
    }

    override fun onPause() {
        super.onPause()
        sp.edit().putInt("count_reserved", viewModel.counter.value ?: 0)
    }

}